package qdrant

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"os"
	"path/filepath"
	"sync"
	"time"

	"mcp-server/internal/qdrant"
	"mcp-server/internal/storage"
)

// EnhancedQdrantClient 增强的Qdrant客户端实现
type EnhancedQdrantClient struct {
	baseClient  qdrant.QdrantClient
	config      *storage.StorageConfig
	collections map[string]*CollectionData
	indexes     map[string][]*storage.IndexInfo
	stats       *storage.StorageStats
	cache       *VectorCache
	mutex       sync.RWMutex
	initialized bool
}

// CollectionData 集合数据
type CollectionData struct {
	Info          *storage.CollectionInfo
	Vectors       map[string]*storage.VectorData
	LastOptimized time.Time
	mutex         sync.RWMutex
}

// VectorCache 向量缓存
type VectorCache struct {
	data    map[string]*storage.VectorData
	maxSize int
	mutex   sync.RWMutex
}

// NewEnhancedQdrantClient 创建增强的Qdrant客户端
func NewEnhancedQdrantClient(baseClient qdrant.QdrantClient) *EnhancedQdrantClient {
	return &EnhancedQdrantClient{
		baseClient:  baseClient,
		collections: make(map[string]*CollectionData),
		indexes:     make(map[string][]*storage.IndexInfo),
		stats: &storage.StorageStats{
			Collections: make(map[string]*storage.CollectionStats),
		},
	}
}

// Initialize 初始化客户端
func (ec *EnhancedQdrantClient) Initialize(config *storage.StorageConfig) error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	log.Println("正在初始化增强Qdrant客户端...")

	ec.config = config

	// 初始化基础客户端
	if err := ec.baseClient.Initialize(config.QdrantConfig); err != nil {
		return fmt.Errorf("初始化基础客户端失败: %w", err)
	}

	// 初始化缓存
	if config.EnableCache {
		ec.cache = &VectorCache{
			data:    make(map[string]*storage.VectorData),
			maxSize: config.CacheSize,
		}
	}

	// 加载现有集合信息
	if err := ec.loadCollections(); err != nil {
		log.Printf("加载集合信息失败: %v", err)
	}

	// 启动自动优化
	if config.AutoOptimize {
		go ec.startAutoOptimize()
	}

	ec.initialized = true
	log.Println("增强Qdrant客户端初始化完成")

	return nil
}

// Close 关闭客户端
func (ec *EnhancedQdrantClient) Close() error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	log.Println("正在关闭增强Qdrant客户端...")

	// 保存集合信息
	if err := ec.saveCollections(); err != nil {
		log.Printf("保存集合信息失败: %v", err)
	}

	// 关闭基础客户端
	if err := ec.baseClient.Close(); err != nil {
		return fmt.Errorf("关闭基础客户端失败: %w", err)
	}

	ec.initialized = false
	log.Println("增强Qdrant客户端已关闭")

	return nil
}

// HealthCheck 健康检查
func (ec *EnhancedQdrantClient) HealthCheck() error {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	return ec.baseClient.HealthCheck()
}

// IsReady 检查是否就绪
func (ec *EnhancedQdrantClient) IsReady() bool {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	return ec.initialized && ec.baseClient.HealthCheck() == nil
}

// CreateCollection 创建集合
func (ec *EnhancedQdrantClient) CreateCollection(ctx context.Context, name string, config *storage.CollectionConfig) error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	log.Printf("正在创建集合: %s", name)

	// 检查集合是否已存在
	if _, exists := ec.collections[name]; exists {
		return fmt.Errorf("集合 %s 已存在", name)
	}

	// 创建基础集合
	qdrantConfig := qdrant.CollectionConfig{
		VectorSize: config.VectorSize,
		Distance:   config.Distance,
	}

	if err := ec.baseClient.CreateCollection(name, qdrantConfig); err != nil {
		return fmt.Errorf("创建基础集合失败: %w", err)
	}

	// 创建集合数据
	collectionData := &CollectionData{
		Info: &storage.CollectionInfo{
			Name:         name,
			VectorCount:  0,
			VectorSize:   config.VectorSize,
			Distance:     config.Distance,
			Status:       "active",
			IndexedCount: 0,
			Config:       config,
			CreatedAt:    time.Now(),
			UpdatedAt:    time.Now(),
		},
		Vectors:       make(map[string]*storage.VectorData),
		LastOptimized: time.Now(),
	}

	ec.collections[name] = collectionData

	// 创建默认索引
	if config.IndexType != "" {
		indexConfig := &storage.IndexConfig{
			Name:       "default",
			Type:       config.IndexType,
			Parameters: config.IndexParams,
		}
		if err := ec.createIndexInternal(name, indexConfig); err != nil {
			log.Printf("创建默认索引失败: %v", err)
		}
	}

	// 更新统计信息
	ec.updateStats()

	log.Printf("集合 %s 创建成功", name)
	return nil
}

// DeleteCollection 删除集合
func (ec *EnhancedQdrantClient) DeleteCollection(ctx context.Context, name string) error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	log.Printf("正在删除集合: %s", name)

	// 检查集合是否存在
	if _, exists := ec.collections[name]; !exists {
		return fmt.Errorf("集合 %s 不存在", name)
	}

	// 删除基础集合
	if err := ec.baseClient.DeleteCollection(name); err != nil {
		return fmt.Errorf("删除基础集合失败: %w", err)
	}

	// 删除集合数据
	delete(ec.collections, name)
	delete(ec.indexes, name)

	// 清理缓存
	if ec.cache != nil {
		ec.cache.clearCollection(name)
	}

	// 更新统计信息
	ec.updateStats()

	log.Printf("集合 %s 删除成功", name)
	return nil
}

// GetCollectionInfo 获取集合信息
func (ec *EnhancedQdrantClient) GetCollectionInfo(ctx context.Context, name string) (*storage.CollectionInfo, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	collectionData, exists := ec.collections[name]
	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", name)
	}

	collectionData.mutex.RLock()
	defer collectionData.mutex.RUnlock()

	// 更新向量计数
	info := *collectionData.Info
	info.VectorCount = int64(len(collectionData.Vectors))
	info.UpdatedAt = time.Now()

	return &info, nil
}

// ListCollections 列出所有集合
func (ec *EnhancedQdrantClient) ListCollections(ctx context.Context) ([]string, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	collections := make([]string, 0, len(ec.collections))
	for name := range ec.collections {
		collections = append(collections, name)
	}

	return collections, nil
}

// CollectionExists 检查集合是否存在
func (ec *EnhancedQdrantClient) CollectionExists(ctx context.Context, name string) (bool, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return false, fmt.Errorf("客户端未初始化")
	}

	_, exists := ec.collections[name]
	return exists, nil
}

// InsertVector 插入单个向量
func (ec *EnhancedQdrantClient) InsertVector(ctx context.Context, collection string, vector *storage.VectorData) error {
	return ec.InsertVectors(ctx, collection, []*storage.VectorData{vector})
}

// InsertVectors 批量插入向量
func (ec *EnhancedQdrantClient) InsertVectors(ctx context.Context, collection string, vectors []*storage.VectorData) error {
	ec.mutex.RLock()
	collectionData, exists := ec.collections[collection]
	ec.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	log.Printf("正在向集合 %s 插入 %d 个向量", collection, len(vectors))

	// 转换为基础向量格式
	qdrantVectors := make([]qdrant.Vector, len(vectors))
	for i, v := range vectors {
		// 设置元数据
		if v.Metadata == nil {
			v.Metadata = &storage.VectorMetadata{
				CreatedAt: time.Now(),
				UpdatedAt: time.Now(),
				Version:   1,
			}
		}

		qdrantVectors[i] = qdrant.Vector{
			ID:      v.ID,
			Vector:  v.Vector,
			Payload: v.Payload,
		}
	}

	// 插入到基础客户端
	if err := ec.baseClient.InsertVectors(qdrantVectors); err != nil {
		return fmt.Errorf("插入向量失败: %w", err)
	}

	// 更新集合数据
	collectionData.mutex.Lock()
	for _, v := range vectors {
		collectionData.Vectors[v.ID] = v

		// 更新缓存
		if ec.cache != nil {
			ec.cache.set(collection+":"+v.ID, v)
		}
	}
	collectionData.Info.VectorCount = int64(len(collectionData.Vectors))
	collectionData.Info.UpdatedAt = time.Now()
	collectionData.mutex.Unlock()

	// 更新统计信息
	ec.updateCollectionStats(collection)

	log.Printf("成功插入 %d 个向量到集合 %s", len(vectors), collection)
	return nil
}

// UpdateVector 更新向量
func (ec *EnhancedQdrantClient) UpdateVector(ctx context.Context, collection string, id string, vector *storage.VectorData) error {
	ec.mutex.RLock()
	collectionData, exists := ec.collections[collection]
	ec.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	collectionData.mutex.Lock()
	defer collectionData.mutex.Unlock()

	// 检查向量是否存在
	existing, exists := collectionData.Vectors[id]
	if !exists {
		return fmt.Errorf("向量 %s 不存在", id)
	}

	// 更新元数据
	if vector.Metadata == nil {
		vector.Metadata = existing.Metadata
	}
	if vector.Metadata != nil {
		vector.Metadata.UpdatedAt = time.Now()
		vector.Metadata.Version++
	}

	// 删除旧向量并插入新向量
	if err := ec.baseClient.DeleteVectors([]string{id}); err != nil {
		return fmt.Errorf("删除旧向量失败: %w", err)
	}

	qdrantVector := qdrant.Vector{
		ID:      vector.ID,
		Vector:  vector.Vector,
		Payload: vector.Payload,
	}

	if err := ec.baseClient.InsertVectors([]qdrant.Vector{qdrantVector}); err != nil {
		return fmt.Errorf("插入新向量失败: %w", err)
	}

	// 更新集合数据
	collectionData.Vectors[id] = vector

	// 更新缓存
	if ec.cache != nil {
		ec.cache.set(collection+":"+id, vector)
	}

	collectionData.Info.UpdatedAt = time.Now()

	log.Printf("向量 %s 更新成功", id)
	return nil
}

// DeleteVector 删除单个向量
func (ec *EnhancedQdrantClient) DeleteVector(ctx context.Context, collection string, id string) error {
	return ec.DeleteVectors(ctx, collection, []string{id})
}

// DeleteVectors 批量删除向量
func (ec *EnhancedQdrantClient) DeleteVectors(ctx context.Context, collection string, ids []string) error {
	ec.mutex.RLock()
	collectionData, exists := ec.collections[collection]
	ec.mutex.RUnlock()

	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	log.Printf("正在从集合 %s 删除 %d 个向量", collection, len(ids))

	// 从基础客户端删除
	if err := ec.baseClient.DeleteVectors(ids); err != nil {
		return fmt.Errorf("删除向量失败: %w", err)
	}

	// 更新集合数据
	collectionData.mutex.Lock()
	deleted := 0
	for _, id := range ids {
		if _, exists := collectionData.Vectors[id]; exists {
			delete(collectionData.Vectors, id)
			deleted++

			// 清理缓存
			if ec.cache != nil {
				ec.cache.delete(collection + ":" + id)
			}
		}
	}
	collectionData.Info.VectorCount = int64(len(collectionData.Vectors))
	collectionData.Info.UpdatedAt = time.Now()
	collectionData.mutex.Unlock()

	// 更新统计信息
	ec.updateCollectionStats(collection)

	log.Printf("成功删除 %d 个向量", deleted)
	return nil
}

// GetVector 获取向量
func (ec *EnhancedQdrantClient) GetVector(ctx context.Context, collection string, id string) (*storage.VectorData, error) {
	// 先检查缓存
	if ec.cache != nil {
		if vector := ec.cache.get(collection + ":" + id); vector != nil {
			return vector, nil
		}
	}

	ec.mutex.RLock()
	collectionData, exists := ec.collections[collection]
	ec.mutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	collectionData.mutex.RLock()
	vector, exists := collectionData.Vectors[id]
	collectionData.mutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("向量 %s 不存在", id)
	}

	// 更新缓存
	if ec.cache != nil {
		ec.cache.set(collection+":"+id, vector)
	}

	return vector, nil
}

// SearchVectors 搜索向量
func (ec *EnhancedQdrantClient) SearchVectors(ctx context.Context, collection string, query *storage.SearchQuery) (*storage.SearchResult, error) {
	startTime := time.Now()

	ec.mutex.RLock()
	_, exists := ec.collections[collection]
	ec.mutex.RUnlock()

	if !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	// 构建查询向量
	queryVector := qdrant.Vector{
		Vector: query.Vector,
	}

	// 执行搜索
	results, err := ec.baseClient.SearchVectors(queryVector, query.Limit)
	if err != nil {
		return nil, fmt.Errorf("搜索失败: %w", err)
	}

	// 转换结果
	hits := make([]*storage.SearchHit, 0, len(results))
	for _, result := range results {
		if result.Score >= query.Threshold {
			hit := &storage.SearchHit{
				ID:      result.ID,
				Score:   result.Score,
				Payload: result.Payload,
			}

			// 根据需要添加向量
			if query.WithVector {
				if vector, err := ec.GetVector(ctx, collection, result.ID); err == nil {
					hit.Vector = vector.Vector
				}
			}

			hits = append(hits, hit)
		}
	}

	// 应用偏移量
	if query.Offset > 0 && query.Offset < len(hits) {
		hits = hits[query.Offset:]
	}

	searchResult := &storage.SearchResult{
		Hits:      hits,
		Total:     int64(len(hits)),
		QueryTime: time.Since(startTime),
	}

	// 更新搜索统计
	ec.updateSearchStats(collection, time.Since(startTime))

	return searchResult, nil
}

// SearchSimilar 搜索相似向量
func (ec *EnhancedQdrantClient) SearchSimilar(ctx context.Context, collection string, vector []float32, limit int, threshold float32) (*storage.SearchResult, error) {
	query := &storage.SearchQuery{
		Vector:      vector,
		Limit:       limit,
		Threshold:   threshold,
		WithPayload: true,
		WithVector:  false,
	}

	return ec.SearchVectors(ctx, collection, query)
}

// CreateIndex 创建索引
func (ec *EnhancedQdrantClient) CreateIndex(ctx context.Context, collection string, config *storage.IndexConfig) error {
	return ec.createIndexInternal(collection, config)
}

// DeleteIndex 删除索引
func (ec *EnhancedQdrantClient) DeleteIndex(ctx context.Context, collection string, indexName string) error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	// 检查集合是否存在
	if _, exists := ec.collections[collection]; !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	// 删除索引信息
	if indexes, exists := ec.indexes[collection]; exists {
		for i, index := range indexes {
			if index.Name == indexName {
				ec.indexes[collection] = append(indexes[:i], indexes[i+1:]...)
				break
			}
		}
	}

	log.Printf("索引 %s 已从集合 %s 删除", indexName, collection)
	return nil
}

// GetIndexInfo 获取索引信息
func (ec *EnhancedQdrantClient) GetIndexInfo(ctx context.Context, collection string) ([]*storage.IndexInfo, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	// 检查集合是否存在
	if _, exists := ec.collections[collection]; !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	indexes, exists := ec.indexes[collection]
	if !exists {
		return []*storage.IndexInfo{}, nil
	}

	return indexes, nil
}

// OptimizeIndex 优化索引
func (ec *EnhancedQdrantClient) OptimizeIndex(ctx context.Context, collection string) error {
	ec.mutex.Lock()
	defer ec.mutex.Unlock()

	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	collectionData, exists := ec.collections[collection]
	if !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	// 检查是否需要优化
	if time.Since(collectionData.LastOptimized) < ec.config.OptimizeInterval {
		return nil
	}

	log.Printf("正在优化集合 %s 的索引", collection)

	// 这里应该调用实际的索引优化逻辑
	// 目前使用模拟实现
	collectionData.LastOptimized = time.Now()

	log.Printf("集合 %s 索引优化完成", collection)
	return nil
}

// BatchInsert 批量插入
func (ec *EnhancedQdrantClient) BatchInsert(ctx context.Context, collection string, vectors []*storage.VectorData, batchSize int) (*storage.BatchResult, error) {
	startTime := time.Now()
	result := &storage.BatchResult{
		Total: len(vectors),
	}

	// 分批处理
	for i := 0; i < len(vectors); i += batchSize {
		end := i + batchSize
		if end > len(vectors) {
			end = len(vectors)
		}

		batch := vectors[i:end]
		if err := ec.InsertVectors(ctx, collection, batch); err != nil {
			result.Failed += len(batch)
			result.Errors = append(result.Errors, fmt.Sprintf("批次 %d-%d: %v", i, end-1, err))
		} else {
			result.Successful += len(batch)
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// BatchUpdate 批量更新
func (ec *EnhancedQdrantClient) BatchUpdate(ctx context.Context, collection string, updates []*storage.VectorUpdate, batchSize int) (*storage.BatchResult, error) {
	startTime := time.Now()
	result := &storage.BatchResult{
		Total: len(updates),
	}

	// 分批处理
	for i := 0; i < len(updates); i += batchSize {
		end := i + batchSize
		if end > len(updates) {
			end = len(updates)
		}

		batch := updates[i:end]
		for _, update := range batch {
			vector := &storage.VectorData{
				ID:      update.ID,
				Vector:  update.Vector,
				Payload: update.Payload,
			}

			if err := ec.UpdateVector(ctx, collection, update.ID, vector); err != nil {
				result.Failed++
				result.Errors = append(result.Errors, fmt.Sprintf("更新 %s: %v", update.ID, err))
			} else {
				result.Successful++
			}
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// BatchDelete 批量删除
func (ec *EnhancedQdrantClient) BatchDelete(ctx context.Context, collection string, ids []string, batchSize int) (*storage.BatchResult, error) {
	startTime := time.Now()
	result := &storage.BatchResult{
		Total: len(ids),
	}

	// 分批处理
	for i := 0; i < len(ids); i += batchSize {
		end := i + batchSize
		if end > len(ids) {
			end = len(ids)
		}

		batch := ids[i:end]
		if err := ec.DeleteVectors(ctx, collection, batch); err != nil {
			result.Failed += len(batch)
			result.Errors = append(result.Errors, fmt.Sprintf("批次 %d-%d: %v", i, end-1, err))
		} else {
			result.Successful += len(batch)
		}
	}

	result.ProcessTime = time.Since(startTime)
	return result, nil
}

// GetStorageStats 获取存储统计
func (ec *EnhancedQdrantClient) GetStorageStats(ctx context.Context) (*storage.StorageStats, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	// 更新统计信息
	ec.updateStats()

	return ec.stats, nil
}

// GetCollectionStats 获取集合统计
func (ec *EnhancedQdrantClient) GetCollectionStats(ctx context.Context, collection string) (*storage.CollectionStats, error) {
	ec.mutex.RLock()
	defer ec.mutex.RUnlock()

	if !ec.initialized {
		return nil, fmt.Errorf("客户端未初始化")
	}

	// 检查集合是否存在
	if _, exists := ec.collections[collection]; !exists {
		return nil, fmt.Errorf("集合 %s 不存在", collection)
	}

	stats, exists := ec.stats.Collections[collection]
	if !exists {
		return &storage.CollectionStats{
			Name: collection,
		}, nil
	}

	return stats, nil
}

// createIndexInternal 内部创建索引方法
func (ec *EnhancedQdrantClient) createIndexInternal(collection string, config *storage.IndexConfig) error {
	if !ec.initialized {
		return fmt.Errorf("客户端未初始化")
	}

	// 检查集合是否存在
	if _, exists := ec.collections[collection]; !exists {
		return fmt.Errorf("集合 %s 不存在", collection)
	}

	log.Printf("正在为集合 %s 创建索引 %s", collection, config.Name)

	// 创建索引信息
	indexInfo := &storage.IndexInfo{
		Name:       config.Name,
		Type:       config.Type,
		Status:     "active",
		Parameters: config.Parameters,
		CreatedAt:  time.Now(),
	}

	// 添加到索引列表
	if ec.indexes[collection] == nil {
		ec.indexes[collection] = []*storage.IndexInfo{}
	}
	ec.indexes[collection] = append(ec.indexes[collection], indexInfo)

	log.Printf("索引 %s 创建成功", config.Name)
	return nil
}

// 辅助方法

// loadCollections 加载集合信息
func (ec *EnhancedQdrantClient) loadCollections() error {
	if ec.config == nil || ec.config.QdrantConfig == nil {
		return nil
	}

	dataPath := ec.config.QdrantConfig.DataPath
	collectionsFile := filepath.Join(dataPath, "collections.json")

	if _, err := os.Stat(collectionsFile); os.IsNotExist(err) {
		return nil
	}

	data, err := os.ReadFile(collectionsFile)
	if err != nil {
		return err
	}

	return json.Unmarshal(data, &ec.collections)
}

// saveCollections 保存集合信息
func (ec *EnhancedQdrantClient) saveCollections() error {
	if ec.config == nil || ec.config.QdrantConfig == nil {
		return nil
	}

	dataPath := ec.config.QdrantConfig.DataPath
	if err := os.MkdirAll(dataPath, 0755); err != nil {
		return err
	}

	collectionsFile := filepath.Join(dataPath, "collections.json")
	data, err := json.MarshalIndent(ec.collections, "", "  ")
	if err != nil {
		return err
	}

	return os.WriteFile(collectionsFile, data, 0644)
}

// updateStats 更新统计信息
func (ec *EnhancedQdrantClient) updateStats() {
	ec.stats.TotalCollections = int64(len(ec.collections))

	var totalVectors int64
	for name, collection := range ec.collections {
		collection.mutex.RLock()
		vectorCount := int64(len(collection.Vectors))
		collection.mutex.RUnlock()

		totalVectors += vectorCount

		if ec.stats.Collections[name] == nil {
			ec.stats.Collections[name] = &storage.CollectionStats{}
		}
		ec.stats.Collections[name].VectorCount = vectorCount
		ec.stats.Collections[name].LastUpdated = time.Now()
	}

	ec.stats.TotalVectors = totalVectors
}

// updateCollectionStats 更新集合统计
func (ec *EnhancedQdrantClient) updateCollectionStats(collection string) {
	if ec.stats.Collections[collection] == nil {
		ec.stats.Collections[collection] = &storage.CollectionStats{
			Name: collection,
		}
	}

	stats := ec.stats.Collections[collection]
	if collectionData, exists := ec.collections[collection]; exists {
		collectionData.mutex.RLock()
		stats.VectorCount = int64(len(collectionData.Vectors))
		collectionData.mutex.RUnlock()
	}
	stats.LastUpdated = time.Now()
}

// updateSearchStats 更新搜索统计
func (ec *EnhancedQdrantClient) updateSearchStats(collection string, queryTime time.Duration) {
	if ec.stats.Collections[collection] == nil {
		ec.stats.Collections[collection] = &storage.CollectionStats{
			Name: collection,
		}
	}

	stats := ec.stats.Collections[collection]
	stats.QueryCount++

	// 计算平均查询时间
	if stats.QueryCount == 1 {
		stats.AvgQueryTime = float64(queryTime.Milliseconds())
	} else {
		stats.AvgQueryTime = (stats.AvgQueryTime*float64(stats.QueryCount-1) + float64(queryTime.Milliseconds())) / float64(stats.QueryCount)
	}
}

// startAutoOptimize 启动自动优化
func (ec *EnhancedQdrantClient) startAutoOptimize() {
	ticker := time.NewTicker(ec.config.OptimizeInterval)
	defer ticker.Stop()

	for range ticker.C {
		if !ec.initialized {
			break
		}

		ec.mutex.RLock()
		collections := make([]string, 0, len(ec.collections))
		for name := range ec.collections {
			collections = append(collections, name)
		}
		ec.mutex.RUnlock()

		for _, collection := range collections {
			if err := ec.OptimizeIndex(context.Background(), collection); err != nil {
				log.Printf("自动优化集合 %s 失败: %v", collection, err)
			}
		}
	}
}

// VectorCache 方法

// get 获取缓存的向量
func (vc *VectorCache) get(key string) *storage.VectorData {
	vc.mutex.RLock()
	defer vc.mutex.RUnlock()

	return vc.data[key]
}

// set 设置缓存
func (vc *VectorCache) set(key string, vector *storage.VectorData) {
	vc.mutex.Lock()
	defer vc.mutex.Unlock()

	// 如果缓存已满，清理一些条目
	if len(vc.data) >= vc.maxSize {
		// 简单的清理策略：清理一半
		count := 0
		for k := range vc.data {
			delete(vc.data, k)
			count++
			if count >= vc.maxSize/2 {
				break
			}
		}
	}

	vc.data[key] = vector
}

// delete 删除缓存
func (vc *VectorCache) delete(key string) {
	vc.mutex.Lock()
	defer vc.mutex.Unlock()

	delete(vc.data, key)
}

// clearCollection 清理集合相关的缓存
func (vc *VectorCache) clearCollection(collection string) {
	vc.mutex.Lock()
	defer vc.mutex.Unlock()

	prefix := collection + ":"
	for key := range vc.data {
		if len(key) > len(prefix) && key[:len(prefix)] == prefix {
			delete(vc.data, key)
		}
	}
}
